import {messages} from "share/common";
import React from 'react'
import { Button,Row,Col,Select,Input,Form,Radio,message,Tag, Tooltip } from 'antd'
import menuRoute from 'routes/menuRoute'
import 'styles/expense-reimbursement-control/mileage-subsidy/mileage-subsidy.scss'
import mileageSubsidyService from 'containers/expense-reimbursement-control/mileage-subsidy/mileage-subsidy.service'
const FormItem = Form.Item
const RadioGroup = Radio.Group;
const Option = Select.Option;
class StaircaseMileageSetting extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      susidyUrl: menuRoute.getRouteItem('mileage-subsidy','key'),
      mileageData:'',
      loading:false,
      type:'',
      pageNo:0,
      pageSize:10,
      steps:[],
      unitAmoutRadioValue:'',
      mileageRadioValue:'',
      unitAmountKey:'',
      unitAmountChangeKey:'',
      unitAmoutChangeOptions:[
        {
          key:'more',
          name: messages('setting.key797'/*修改后金额不可大于原补贴金额*/)
        },
        {
          key:'less',
          name: messages('setting.key798'/*修改后金额可以大于原补贴金额*/)
        }
      ],
      params:{},
      tags: [],
      inputVisible: false,
      inputValue: '',
      manyInvoice: ''
    }
  }

  handleClose = (removedTag) => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    this.setState({ tags });
  }

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  }

  handleInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  }

  saveInputRef = input => this.input = input

  handleBack = ()=>{
    this.context.router.push(this.state.susidyUrl.url)
  };

  componentWillMount(){
    this.getSteps()
  }

  getSteps(){
    let param = {
      pageNo:this.state.pageNo,
      pageSize:this.state.pageSize
    }
    mileageSubsidyService.getTieredRuleList(param).then((response) =>{
      let tempSteps = []
      response.data.stepVOs && response.data.stepVOs.map((item,index) =>{
        if(index !== response.data.stepVOs.length-1){
          tempSteps.push(item.endUnit)
        }
      })
      this.setState({
        tags:tempSteps,
        manyInvoice: response.data.manyInvoice || 1
      })
    })
  }

  handleInputConfirm = () => {
    const state = this.state;
    const inputValue = state.inputValue;
    console.log(inputValue)
    let tags = state.tags;
    const reg = /^[0-9]+([.]{1}[0-9]{1,2})?$/;
    if(!reg.test(inputValue)){
      message.error(messages('setting.key799'/*输入不合规范，请按照范例样式输入*/));
      return;
    }else if(inputValue < tags[tags.length-1]){
      message.error( messages('setting.key800'/*里程数不能小于或等于前面一位数*/))
      return;
    } else{
      tags = [...tags, Number(inputValue)];
    }
    this.setState({
      tags,
      inputVisible: false,
      inputValue: '',
    });
  }

  handleSubmit = (e)=>{
    e.preventDefault();
    if(this.state.tags.includes(Number(this.state.inputValue)) || this.state.inputValue === ''){
      let { params, tags, manyInvoice } = this.state;
      tags.splice(0, 0, 0);
      tags.splice(tags.length, 0, -1);
      params.stepMileages = tags;
      params.manyInvoice = manyInvoice;
      // this.checkInputValue()
      let hide = message.loading(messages('setting.key801'/*正在保存*/));
      mileageSubsidyService.addStep(params).then((response) =>{
        hide();
        message.success(`${messages('common.save.success',{name:""})}`);
        this.props.form.resetFields();
        this.handleBack()
      }).catch(e=>{
        hide();
        this.setState({ loading: false });
        message.error(`${messages('common.save.filed')}, ${e.response.data.message}`)
      });
    }else{
      this.handleInputConfirm()
    }
  };

  render() {
    const { tags,inputVisible,inputValue } = this.state;

    return (
      <div className="mileage-subsidy">
          <Row>
              <Col span={8}>
                <div className="mode">{messages('setting.key780'/*当前模式：阶梯模式*/)}</div>
              </Col>
              <Col span={12}/>
              <Col span={4}>
              </Col>
          </Row>
          {/*<Form onSubmit={this.handleSubmit} style={{marginTop: 20,color: '#656565'}}>*/}
              <div>
                  <p className="tip-title"><span className="tip">*</span><span>{messages('setting.key802'/*设置阶梯里程(KM)*/)}{/*设置阶梯里程(KM)*/}：</span></p>
                  <p className="tip-content">{messages('setting.key803'/*请输入阶梯里程数，数字从小到大输入，最多一位小数；数字之间以【Enter】分隔，中间不能有空格。*/)}{/*请输入阶梯里程数，数字从小到大输入，最多一位小数；数字之间以【Enter】分隔，中间不能有空格*/}</p>
                  <p className="tip-content">{messages('setting.key804'/*范例：输入100/200/300，则：0.00＜第一阶梯≤100.00，100.00＜第二阶梯≤200.00，200.00＜第三阶梯≤300.00，300.00＜第四阶梯≤无限*/)}{/*范例：输入100/200/300，则：0＜第一阶梯≤100.0，100.0＜第二阶梯≤200.0，200.0＜第三阶梯≤300.0，300.0＜第四阶梯≤无限*/}</p>
                  <Row>
                      <Col span={1}>
                          <Button disabled>0</Button>
                      </Col>
                      <Col span={1}><span className="line">-</span></Col>
                      <Col span={14} className='tag-line'>
                          <div>
                            {tags.map((tag, index) => {
                              const isLongTag = tag.length > 20;
                              let showTag=tag;
                              if(typeof tag ==='number'){
                                showTag=tag.toFixed(2);
                              }
                              const tagElem = (
                                <Tag color='#4B8DFF' key={tag} closable={true} afterClose={() => this.handleClose(tag)}>
                                  {isLongTag ? `${tag.slice(0, 20)}...` : showTag}
                                </Tag>
                              );
                              return isLongTag ? <Tooltip title={showTag}>{tagElem}</Tooltip> : tagElem;
                            })}
                            {inputVisible && (
                              <Input
                                ref={this.saveInputRef}
                                type="text" size="small"
                                style={{ width: 78 }}
                                value={inputValue}
                                onChange={this.handleInputChange}
                                onBlur={this.handleInputConfirm}
                                onPressEnter={this.handleInputConfirm}
                              />
                            )}
                            {!inputVisible && <Button size="small" type="dashed" onClick={this.showInput}>+ {messages('setting.key805'/*新的里程*/)}{/*新的里程*/}</Button>}
                          </div>
                      </Col>
                      <Col span={1}><span className="line">-</span></Col>
                      <Col span={1}>
                          <Button disabled>{messages('setting.key806'/*无限*/)}{/*无限*/}</Button>
                      </Col>
                      <Col span={2}/>
                  </Row>
                  <div className="summary">
                      <div className="summary-mode">{messages('setting.key807'/*里程汇总方式*/)}{/*里程汇总方式*/}：</div>
                      <div className="summary-mode">{messages('setting.key808'/*按自然月汇总里程，员工每月生成 1 笔里程补贴总费用*/)}{/*按自然月汇总里程，员工每月生成 1 笔里程补贴总费用*/}</div>
                  </div>
              </div>
              <div className="button-area">
                  <Button type="primary"  htmlType="submit" onClick={this.handleSubmit}>{messages("common.save") /*保存*/}</Button>
                  <Button onClick={()=>this.handleBack()} className="cancelButton">{messages('common.cancel')/*取消*/}</Button>
              </div>
          {/*</Form>*/}
      </div>
    )
  }
}
StaircaseMileageSetting.contextTypes = {
    router: React.PropTypes.object
};

const wrappedStaircaseMileageSetting =  Form.create()(StaircaseMileageSetting);

export default wrappedStaircaseMileageSetting;
